package com.freewater.javabase.demo.designpattern.templatemethod;

import java.util.Random;

public abstract class AbstractSetting {
    private static final Random random = new Random();

    public final String getSetting(String key) {
        String value = lookupCache(key);
        if (value == null) {
            value = readFromDatabase(key);
            System.out.println("[DEBUG] load from db: " + key + " = " + value);
            putIntoCache(key, value);
        } else {
            System.out.println("[DEBUG] load from cache: " + key + " = " + value);
        }
        return value;
    }

    protected abstract String lookupCache(String key);

    protected abstract void putIntoCache(String key, String value);

    private String readFromDatabase(String key) {
        return key + ":" + random.nextInt(100);
    }
}
